package com.example.javamaday.encrypt_decrypt;

import android.support.annotation.RequiresApi;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class RASDemo {


    @RequiresApi(api = 26)
    public static void main(String[] args) throws Exception{

        // 创建密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = keyPair.getPrivate();

        PublicKey publicKey = keyPair.getPublic();

        byte[] privateKeyEncoded = privateKey.getEncoded();

        byte[] publicKeyEncoded = publicKey.getEncoded();

        //System.out.println(new String(Base64.getEncoder().encode(publicKeyEncoded)));
        //System.out.println(new String(Base64.getEncoder().encode(privateKeyEncoded)));

        decode(publicKey, encode(privateKey));
    }
    @RequiresApi(api = 26)
    private static byte[] encode(Key key) throws Exception {
        String input = "RenHui"; // 原文
        String transformation = "RSA";  // 算法
        Cipher cipher = Cipher.getInstance(transformation);
        /**
         * 进行加密初始化，第一个参数表示模式，第二个参数表示加密的规则
         */
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 调用加密的方法, 参数为原文的字节数组
        byte[] bytes = cipher.doFinal(input.getBytes());
        // 使用Base64加密后，在打印密文
        byte[] enCode = Base64.getEncoder().encode(bytes);
        System.out.println("Encode Content = " + new String(enCode));
        return enCode;
    }

    @RequiresApi(api = 26)
    private static void decode(Key key, byte[] encodeContent) throws Exception {
        String transformation = "RSA";  // 算法
        Cipher cipher = Cipher.getInstance(transformation);

        /**
         * 进行加密初始化，第一个参数表示模式，第二个参数表示加密的规则
         */
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 调用加密的方法, 参数为原文的字节数组
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(encodeContent));
        System.out.println("Decode Content = " + new String(bytes));
    }


}
